package leetcode.editor.cn;

import java.util.Arrays;

public class ZuiXiaoDeKGeShu {
    public int[] getLeastNumbers(int[] arr, int k) {
        if (arr == null || arr.length == 0) return null;
        quickSort(arr, 0, arr.length - 1);
        int[] res = new int[k];
        for (int i = 0; i < k; i++) {
            res[i] = arr[i];
        }
        return res;
    }

    void quickSort(int[] arr, int l, int r) {
        // 不要忘了递归出口,子数组长度为1时结束
        if (l >= r) return;
        int key = arr[l];
        int i = l, j = r;
        while (i < j) {
            // 先从后往前找，这样 i==j时，就是要与key交换的数组元素
            while (i < j && arr[j] >= key) j--;
            while (i < j && arr[i] <= key) i++;
            swap(arr, i, j);
        }
        swap(arr, l, i);
        quickSort(arr, l, i - 1);
        quickSort(arr, i + 1, r);
    }

    void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void main(String[] args) {
        int[] arr = {3, 2, 1};
        new ZuiXiaoDeKGeShu().getLeastNumbers(arr, 2);
        System.out.println(Arrays.toString(arr));
    }
}
